import * as loginInfoUtil from './loginInfo.js'
import resource from '../config/resource'

/* global FormData, XMLHttpRequest*/
let _onProgress = function (e) {
  // this is an internal call in XHR to update the progress
  e.percent = (e.loaded / e.total) * 100
}
let _handleUpload = function (file, action) {
  var form = new FormData()
  var xhr = new XMLHttpRequest()
  try {
    form.append('Content-Type', file.type || 'application/octet-stream')
      // our request will have the file in the ['file'] key
    form.append('file', file)
    form.append('sessionId', loginInfoUtil.getInfo().sessionId)
  } catch (err) {
    return
  }

  return new Promise(function (resolve, reject) {
    xhr.upload.addEventListener('progress', _onProgress, false)
    xhr.onreadystatechange = function () {
      if (xhr.readyState < 4) {
        return
      }
      if (xhr.status < 400) {
        var res = JSON.parse(xhr.responseText)
        resolve(res)
      } else {
        var err = JSON.parse(xhr.responseText)
        err.status = xhr.status
        err.statusText = xhr.statusText
        reject(err)
      }
    }
    xhr.onerror = function () {
      var err = JSON.parse(xhr.responseText)
      err.status = xhr.status
      err.statusText = xhr.statusText
      reject(err)
    }

    xhr.open('POST', action, true)
    xhr.send(form)
  })
}
let fileUpload = function (action, files) {
    // a hack to push all the Promises into a new array
  action = resource.root + '/' + action
  var arrayOfPromises = Array.prototype.slice.call(files, 0).map((file) => _handleUpload(file, action))
    // wait for everything to finish
  return Promise.all(arrayOfPromises)
}

let plugin = (Vue) => {
  if (plugin.installed) {
    return
  }
  Vue.prototype.$upload = fileUpload
}

export default plugin
